package rsj.service.export.product.produce;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.TableNode;
import common.util.DateTimeFormatterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import rsj.api.org.entity.CurrentTableColumn;
import rsj.api.org.entity.UsageReportParam;
import rsj.service.export.product.IProductExportCurrentTable;
import rsj.service.usage.IUsageTemplateMethod;
import rsj.sql.product.ProductCurrentDao;

import java.sql.Connection;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 产品管理-导出当前生产环境表格
 *
 * @author yuanqinglong
 * @since 2021/3/5 15:07
 */
@Component
public class ProductProduceCurrentTable implements IProductExportCurrentTable {

    @Autowired
    private ProductCurrentDao productCurrentDao;


    @Override
    public TableNode queryTableByPage(UsageReportParam usageReportParam) {
        return productCurrentDao.productProduceCurrent(usageReportParam);
    }


    /**
     * 导出当前生产环境表格sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    @Override
    public String generateQueryStatement(UsageReportParam usageReportParam) {
        usageReportParam.setEnvironment(IUsageTemplateMethod.PRODUCE_ENVIRONMENT);
        return IProductExportCurrentTable.exportCurrentTableQueryStatement(usageReportParam);
    }

    /**
     * 生成导出的文件名称
     *
     * @param usageReportParam usageReportParam参数
     * @return 文件名
     */
    @Override
    public String generateExportFileName(UsageReportParam usageReportParam) {
        String deadline = Optional.ofNullable(usageReportParam.getStatDate()).map(DateTimeFormatterUtil::localDateFormatterToStringDate).orElseGet(() -> DateTimeFormatterUtil.localDateFormatterToStringDate(LocalDate.now()));
        return this.queryProdNameByStatProdUid(usageReportParam.getStatProdUid()) + "-截至" + deadline + "-生产环境使用情况.xlsx";
    }



    /**
     * 提供扩展的默认方法-根据不同业务情况重写此方法二次处理列表数据
     *
     * @param tableNode        列表数据
     * @param connection       数据库连接
     * @param usageReportParam usageReportParam参数
     * @return 处理后的列表数据
     */
    @Override
    public String processDataAccordingToTheSituation(TableNode tableNode, Connection connection, UsageReportParam usageReportParam) {
        List<CurrentTableColumn> statisticColumnEntities = JSON.parseArray(tableNode.toJson(), CurrentTableColumn.class);
        if (CollectionUtils.isEmpty(statisticColumnEntities)) {
            return tableNode.toJson();
        }
        // 计算剩余量、查询接口的使用量分组累计
        this.queryInterfaceUsageThroughContract(statisticColumnEntities, connection, IUsageTemplateMethod.PRODUCE_ENVIRONMENT, usageReportParam);
        return JSON.toJSONString(statisticColumnEntities);
    }
}
